package com.example.pufang.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.PageParamRequest;
import com.example.exception.PufangException;
import com.example.pufang.mapper.ReportMapper;
import com.example.pufang.pojo.House;
import com.example.pufang.pojo.Report;
import com.example.pufang.pojo.SystemMessage;
import com.example.pufang.pojo.User;
import com.example.pufang.service.HouseService;
import com.example.pufang.service.ReportService;
import com.example.pufang.service.SystemMessageService;
import com.example.pufang.vo.PageListVo;
import com.example.pufang.vo.ReportAdminDetailVo;
import com.example.pufang.vo.ReportAdminListVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl extends ServiceImpl<ReportMapper, Report> implements ReportService {

    @Value("${img.path}")
    private String imgPath;

    @Autowired
    private SystemMessageService systemMessageService;

    @Autowired
    private HouseService houseService;

    @Autowired
    private ReportMapper reportMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean submitReport(Report report, User user) {

        if (StringUtils.isBlank(report.getHouseId())) {
            return false;
        }

        // 保存到系统消息
        SystemMessage systemMessage = new SystemMessage();
        systemMessage.setAdminId(-1)
                .setMessage("您提交的关于\"" + houseService.getById(report.getHouseId()).getTitle()
                        + "\"的举报已经提交，请等待管理员处理。")
                .setReceiverId(user.getId());

        report.setUserId(user.getId());

        systemMessageService.save(systemMessage);

        return this.save(report);
    }

    @Override
    public PageListVo getListByPage(PageParamRequest pageParamRequest, String searchName, String searchReason) {
        PageListVo pageListVo = new PageListVo();

        int start = (pageParamRequest.getPage()-1)* pageParamRequest.getLimit();
        int limit = pageParamRequest.getLimit();

        List<ReportAdminListVo> reportList = reportMapper.getListByPage(start, limit, searchName, searchReason);

        // 将图片url添加地址
        // try {
        //     reportList = reportList.stream().map(e -> {
        //         if (StringUtils.isNotBlank(e.getHousePic())) {
        //             List<String> imgList = (List<String>) JSONArray.parse(e.getHousePic());
        //             ArrayList<String> imgListResult = new ArrayList<>();
        //             imgList.forEach((imgUrl) -> {
        //                 imgListResult.add(imgPath + imgUrl);
        //             });
        //             e.setHousePic(JSON.toJSONString(imgListResult));
        //         }
        //         return e;
        //     }).collect(Collectors.toList());
        // } catch (Exception e) {
        //     e.printStackTrace();
        // }

        // 获取总数
        Long total = baseMapper.count(searchName, searchReason);

        // 获取总页数
        long l = total % pageParamRequest.getLimit();
        long totalPage = 0;
        if (l > 0) {
            totalPage = Math.floorDiv(total, pageParamRequest.getLimit()) + 1;
        } else {
            totalPage = Math.floorDiv(total, pageParamRequest.getLimit());
        }

        pageListVo.setPage((long) pageParamRequest.getPage())
                .setSize((long) pageParamRequest.getLimit())
                .setList(JSONObject.toJSONString(reportList))
                .setTotal(total)
                .setTotalPage(totalPage);

        return pageListVo;
    }

    @Override
    public ReportAdminDetailVo getDetail(String reportId) {
        return baseMapper.getReportDetail(reportId);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean passReport(String reportId, Integer adminId) {

        Report report = this.getById(reportId);

        if (ObjectUtils.isNull(adminId)) {
            throw new PufangException("获取不到当前处理用户");
        }

        if (ObjectUtils.isNull(report)) {
            throw new PufangException("获取不到举报信息");
        }

        House house = houseService.getById(report.getHouseId());
        if (ObjectUtils.isNull(house)) {
            throw new PufangException("获取不到房源信息");
        }

        // 更新房源状态
        house.setIsBan(true);
        houseService.updateById(house);

        // 更新举报记录状态
        report.setAdminId(adminId)
                .setIsHandle(true)
                .setHandleResult(true);

        // 保存到系统消息
        SystemMessage systemMessage = new SystemMessage();
        systemMessage.setAdminId(adminId)
                .setMessage("您提交的关于\"" + houseService.getById(report.getHouseId()).getTitle()
                        + "\"的举报已经通过，当前房源已下架，感谢您的支持。")
                .setReceiverId(report.getUserId());

        systemMessageService.save(systemMessage);

        return this.updateById(report);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean refuseReport(String reportId, Integer adminId) {

        Report report = this.getById(reportId);

        if (ObjectUtils.isNull(adminId)) {
            throw new PufangException("获取不到当前处理用户");
        }

        if (ObjectUtils.isNull(report)) {
            throw new PufangException("获取不到举报信息");
        }

        House house = houseService.getById(report.getHouseId());
        if (ObjectUtils.isNull(house)) {
            throw new PufangException("获取不到房源信息");
        }

        // 保存到系统消息
        SystemMessage systemMessage = new SystemMessage();
        systemMessage.setAdminId(adminId)
                .setMessage("很抱歉，您提交的关于\"" + houseService.getById(report.getHouseId()).getTitle()
                        + "\"的举报没有通过，感谢您的支持。")
                .setReceiverId(report.getUserId());

        systemMessageService.save(systemMessage);

        // 更新举报记录状态
        report.setAdminId(adminId)
                .setIsHandle(true)
                .setHandleResult(false);
        return this.updateById(report);
    }
}
